package sim1011.examples.test1;

import java.util.Random;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class ComponentBehaviour extends CyclicBehaviour {
	private static final long serialVersionUID = -4892058773573619829L;
	private AID[] components;
	
	@Override
	public void action() {
		MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.PROPAGATE);
		ACLMessage msg = myAgent.receive(mt);
		if (msg != null) {
			System.out.println(myAgent.getAID().getName() + " received message from " + msg.getSender().getName());			
			try {
				Random r = new Random(System.currentTimeMillis());
				Thread.sleep(r.nextInt(5000)+1);
				sendMessage();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			block();
		}
	}
	
	private void sendMessage() {
		DFAgentDescription template = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType("sim-type");
		template.addServices(sd);
		try {
			DFAgentDescription[] result = DFService.search(myAgent, template); 
			components = new AID[result.length];
			for (int i = 0; i < result.length; ++i) {
				components[i] = result[i].getName();
			}
			if (result.length != 0) {
				Random r = new Random(System.currentTimeMillis());
				int nr = -1;
				boolean found = false;
				int who = -1;
				while (!found) {
					nr = r.nextInt();
					who = (Math.abs(nr))%(result.length);
					if (!components[who].getName().equalsIgnoreCase(myAgent.getAID().getName()))
						found = true;
				}
				System.out.println("r=" +nr+ " who="+who);
				ACLMessage req = new ACLMessage(ACLMessage.PROPAGATE);
				req.addReceiver(components[who]);
				myAgent.send(req);
			}
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
	}
}
